package com.gxljc.bear.crawler.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

	/**
	 * 在当前日期上添加天数
	 *
	 * @param date
	 * @param day
	 * @return 返回添加天数后的日期
	 */
	public static Date addCalendar(Date date, int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, day);
		return calendar.getTime();
	}

	public static Date minusCalendar(Date date, int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, -1 * day);
		return calendar.getTime();
	}

	public static String dateFormat(Date date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return dateFormat.format(date);
	}

	public static String dateFormat(Date date, String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}

	public static String nowFormat() {
		Date now = new Date();
		final String FORMAT = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT);
		return dateFormat.format(now);
	}

	public static Date parseFormat(String date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return dateFormat.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
			return null;
		}
	}

	public static Date parseFormat(String date, String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		try {
			return dateFormat.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
			return null;
		}
	}

	//格式化日期
	public static String convertStringToDate(Object strObj) {
		if (strObj != null) return convertStringToDate((String) strObj);
		return null;
	}

	//格式化日期
	public static String convertStringToDate(String str) {
		try {
			Calendar c = Calendar.getInstance();
			//Date now = new Date();
			// 12:56 no date
			if (str.indexOf('-') == -1) {
				str = String.format("%d-%d-%d %s", c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), str);
			}
			// 2008-9-25 no time
			if (str.indexOf(':') == -1) {
				str = String.format("%s 00:00", str);
			}
			// 12-03 21:39 no year or 2008-9-25 21:39 complete
			if (str.indexOf('-') <= 2) {
				str = String.format("%d-%s", c.get(Calendar.YEAR), str);
			}
			return str;
		} catch (Exception e) {
			Date now = new Date();
			return DateUtil.dateFormat(now, "yyyy-MM-dd HH:mm");
		}
	}
}
